package top.codedance.iotp.slave.net.handle.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.HexCodec;
import top.codedance.iotp.slave.SlaveApplication;
import top.codedance.iotp.slave.net.handle.AdapterController;
import top.codedance.iotp.slave.service.slave.Slave;
import org.apache.log4j.Logger;

public class OprationController extends AdapterController {
    private static Logger logger = SlaveApplication.getLogger(OprationController.class);

    public String doSubHandler(JSONObject body) {
        try {
            if(body.containsKey("data")){
                HexCodec hc = new HexCodec();
                JSONArray items = body.getJSONArray("data");
                for (int i = 0;i<items.size();i++){
                    JSONObject item = items.getJSONObject(i);
                    int slaveId = item.getIntValue("slaveId");
                    if(SlaveApplication.slaves.containsKey(slaveId)) {
                        Slave slave = SlaveApplication.slaves.get(slaveId);
                        if(slave != null){
                            if(item.containsKey("cmd")){
                                slave.send(hc.toBytes(item.getString("cmd")));
                            }else{
                                slave.send(item.toJSONString().getBytes());
                            }
                        }else{
                            return okResponse("Fail, slave not found.");
                        }
                    }else{
                        return okResponse("Fail, slave not found.");
                    }
                }
                return okResponse("Success");
            }else{
                return okResponse("Fail, parameter error.");
            }
        } catch (Exception e) {
            logger.debug(e.getMessage());
            return response500( "Programe exception");
        }
    }
}
